package org.lboot.flow.module.assign;


import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.AuthService;
import org.lboot.flow.constant.FlowAssignConst;
import org.lboot.jpa.jpa.AbstractJpaCurdExt;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class FlowTaskAssignServiceImpl extends AbstractJpaCurdExt<String,FlowTaskAssign,FlowTaskAssignDAO> implements FlowTaskAssignService{

    AuthService authService;


    @Override
    public List<FlowTaskAssign> getAll(Specification<FlowTaskAssign> specification) {
        return dao.findAll(specification);
    }

    // @TODO 这个应该由第三方进行实现
    @Override
    public List<FlowTaskAssign> getUserAssigns() {
        // 用户ID
        String userId = authService.getUid();

        List<String> roleIds = authService.getRoles();




        // 根据多个条件查询流程任务分配
        Specification<FlowTaskAssign> taskSpec = (root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            // 根据部门查询
//            Predicate p1 = cb.and(
//                    cb.equal(root.get("assignType").as(String.class), FlowAssignConst.DEPT),
//                    cb.equal(root.get("assignId").as(String.class),deptId)
//            );
//            list.add(p1);
            // 根据角色查询
            Predicate p2 = cb.and(
                    cb.equal(root.get("assignType").as(String.class), FlowAssignConst.ROLE),
                    root.get("assignId").in(roleIds)
            );
            list.add(p2);
            // 根据用户查询
            Predicate p3 = cb.and(
                    cb.equal(root.get("assignType").as(String.class), FlowAssignConst.USER),
                    cb.equal(root.get("assignId").as(String.class),userId)
            );
            list.add(p3);
            Predicate[] predicates = new Predicate[list.size()];
            return cb.or(list.toArray(predicates));
        };
        // 获取全部
        return getAll(taskSpec);
    }

    @Override
    public List<FlowTaskAssign> getByFlowCodeAndFlowNodeId(String flowCode, String flowNodeId) {
        return dao.findByFlowCodeAndFlowNodeId(flowCode, flowNodeId);
    }

    @Override
    public List<FlowTaskAssign> deleteByFlowCode(String code) {
        return dao.deleteByFlowCode(code);
    }

    @Override
    public List<FlowTaskAssign> getByFlowCode(String code) {
        return dao.findByFlowCode(code);
    }
}
